<template>
  <view class="container">
    <uni-nav-bar
      :border="false"
      statusBar
      title="外来人员入退申请"
      color="#1F1F1F"
      left-icon="left"
      @clickLeft="onBack"
    >
    </uni-nav-bar>
    <view class="formBox">
      <uni-forms
        ref="valiForm"
        :rules="rules"
        v-model="formData"
        label-position="top"
        label-width="150"
      >
        <uni-forms-item label="入住时间" required name="startDate">
          <uni-datetime-picker
            type="date"
            :start="new Date().getTime()"
            v-model="formData.startDate"
          />
        </uni-forms-item>
        <uni-forms-item label="退房时间" required name="endDate">
          <uni-datetime-picker
            type="date"
            :key="formData.endDate"
            :start="new Date().getTime()"
            v-model="formData.endDate"
          />
        </uni-forms-item>
        <uni-forms-item label="时长(天)" required name="days">
          <uni-number-box disabled v-model="formData.days" />
        </uni-forms-item>
        <uni-forms-item label="入住人" name="occupant">
          <uni-easyinput v-model="formData.occupant" placeholder="请输入" />
        </uni-forms-item>
        <uni-forms-item label="入住人单位" name="occupantUnit">
          <uni-easyinput
            v-model="formData.occupantDeptName"
            placeholder="请输入"
          />
        </uni-forms-item>
        <uni-forms-item label="入住人数" required name="peopleNumber">
          <uni-number-box v-model="formData.peopleNumber" />
        </uni-forms-item>
        <uni-forms-item
          label="入住人员情况说明"
          name="situationExplain"
          required
        >
          <uni-easyinput
            type="textarea"
            v-model="formData.situationExplain"
            placeholder="请输入"
          />
        </uni-forms-item>
      </uni-forms>
      <button class="btn" type="primary" @click="onSubmit('valiForm')">
        提交
      </button>
    </view>
  </view>
</template>

<script>
import _ from 'lodash';
import {
  netCompleteTask,
  netStartWorkFlow,
  addExterPersonApartment,
} from '@/api/workflow';
import FileUploader from '@/components/FileUploader/index.vue';
export default {
  components: {
    FileUploader,
  },
  data() {
    return {
      applicationType: [
        {
          label: '入住',
          text: '入住',
          value: '1',
        },
        {
          label: '换房',
          text: '换房',
          value: '2',
        },
        {
          label: '退房',
          text: '退房',
          value: '3',
        },
      ],
      myErr: '暂无',
      // 表单数据
      formData: { days: 0, endDate: null, peopleNumber: 1 },
      // 规则
      rules: {
        startDate: {
          rules: [
            {
              required: true,
              errorMessage: '请选择入住时间',
            },
          ],
        },
        endDate: {
          rules: [
            {
              required: true,
              errorMessage: '请选择退房时间',
            },
          ],
        },
        days: {
          rules: [
            {
              required: true,
              errorMessage: '请填写时长(天)',
            },
          ],
        },
        peopleNumber: {
          rules: [
            {
              required: true,
              errorMessage: '请填写入住人数',
            },
          ],
        },
        situationExplain: {
          rules: [
            {
              required: true,
              errorMessage: '请填写入住人员情况说明',
            },
          ],
        },
      },
    };
  },
  watch: {
    'formData.startDate': {
      handler(newVal) {
        this.computedDays();
      },
      immediate: false,
      deep: true,
    },
    'formData.endDate': {
      handler(newVal) {
        this.computedDays();
      },
      immediate: false,
      deep: true,
    },
  },
  onLoad(query) {
    if (Object.keys(query).length) {
      // 解码
      this.query = query;
    }
  },
  methods: {
    computedDays() {
      if (this.formData.startDate && this.formData.endDate) {
        const gap =
          Date.parse(new Date(this.formData.endDate)) -
          Date.parse(new Date(this.formData.startDate));
        if (gap >= 0) {
          this.formData.days = gap / (1000 * 60 * 60 * 24) + 1;
        } else {
          uni.showToast({
            title: `入住时间不能晚于退房时间！`,
            icon: 'none',
          });
          this.formData.days = 0;
          this.$nextTick(() => {
            this.formData.endDate = null;
          });
        }
      }
    },
    // 提交
    onSubmit(ref) {
      this.$refs[ref]
        .validate()
        .then((res) => {
          console.log('success', res);
          // loading提示
          uni.showLoading({ title: '操作中' });
          // 提交接口
          let api = addExterPersonApartment;
          let params = res;
          api(params).then((res) => {
            this.onStartWorkFlow(res.data);
          });
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    // 开启工单流
    onStartWorkFlow(data) {
      let params = {
        tableName: 'work_exter_person_apartment',
        businessKey: data.exterPersonApartmentId,
        variables: { entity: data },
      };
      netStartWorkFlow(params).then((res) => {
        this.onCompleteTask(res.data, params);
      });
    },
    // 完成工单流
    onCompleteTask(d, p) {
      let params = {
        taskId: d.taskId,
        variables: {},
        wfCopyList: [],
        messageType: ['1'],
        taskVariables: p.variables,
      };
      netCompleteTask(params).then((res) => {
        uni.hideLoading();
        uni.showToast({
          title: `提交成功`,
        });
        // 重置
        let timer = null;
        timer = setTimeout(() => {
          this.onBack();
          clearTimeout(timer);
        }, 1000);
      });
    },
    // 重置表单
    onReset() {
      this.formData = this.$options.data().formData;
    },
    // 跳转页面
    onLocation(url) {
      uni.navigateTo({
        url,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  min-height: calc(100vh - var(--window-top));
  background: #f2f2f2;
  position: relative;
  display: flex;
  flex-direction: column;
  .formBox {
    padding: 60rpx 48rpx 100rpx;
    background: #fff;
    overflow: hidden;
    .uni-forms {
      min-height: 38vh;
    }
    .myLabel {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .star {
        color: #dd524d;
      }
    }
  }
}
</style>
